import {componentsFnMap} from './config'
// import { useUserStore } from '@/stores/modules/user';

/* 
    执行完此方法后组件信息就会增加focusIndex，boxId，componentValue等信息
*/
export function getPage (layoutArr,pageId,options={downloadFile:false}) {
    let {downloadFile} = options
    let commentJs = `` // 预先准备可用的js的代码
    let focusIndex = 0
    let varCode = ``
    let totalData = `{\n`
    let layoutHtml = layoutArr.map((layoutItem,layoutIndex) => {
        let {children = [],componentName} = layoutItem  
        layoutItem.boxId = `${pageId}_container_${layoutIndex + 1}` // 容器id      
        let layoutOtherOptions = {showSetting:''}
        if (componentName === 'ifNewLayout') {
          layoutItem.formName = layoutItem.formName ? layoutItem.formName : `form${layoutIndex}`
          varCode += `
const ${layoutItem.formName} = reactive({props:{}});
`
          varCode += `
const ${layoutItem.formName}Ref = ref();
`
          totalData += `
  ${layoutItem.formName}Ref,`
          totalData += `
  ${layoutItem.formName},`
          totalData += `
  on${layoutItem.formName}Submit,`
          if (layoutItem.show === false) {
            // 如果设置了隐藏
            let code_show = `card_${layoutItem.formName}Show`
            varCode += `const ${code_show} = ref(false);\n`
            totalData += `
        ${code_show},`
        layoutOtherOptions.showSetting += `\n v-show="${code_show}"`              
          }  
          commentJs +=`\n
async function on${layoutItem.formName}Submit () {
  const props = ${layoutItem.formName}.props;
  console.log(props,${layoutItem.formName}Ref)
  await ${layoutItem.formName}Ref.value.validate((valid, fields) => {
    if (valid) {
      
    }
    });            
  }
          \n`
        }
        let htmlStrArr = []
        let componentRulesCode = ``
        // 容器内组件相关代码生成
        children.forEach((item,index) => {
            item.formItemName = item.formItemName ? item.formItemName : `formItem${index}`
            item.formName = layoutItem.formName
            item.formBoxId = `${layoutItem.boxId}_form`
            item.focusIndex = ++focusIndex
            item.idPrefix = pageId
            item.boxId = `${item.idPrefix}_${item.formItemName ? item.formItemName :'fieldBox'}_${item.focusIndex}` // 修改删除需要此boxId
            item.componentValue = `${item.idPrefix}_${layoutIndex}_${index}`
            let { componentName,formItemName,formName,eventList,busname,required} = item
            if (componentsFnMap[componentName].getScriptStr) {
                commentJs += componentsFnMap[componentName].getScriptStr(item) + '\n'
            }
            if (eventList && eventList.length > 0) {
                commentJs += getEventCode(item)+ '\n'
            }
            if (componentName.startsWith('base')) {
              // 基础组件
              if (componentsFnMap[componentName].getFormItemRules) {
                componentRulesCode += `       ${formItemName}:${componentsFnMap[componentName].getFormItemRules(item)},\n`
              }
            } else if (!['yc-btn-container'].includes(componentName)) {
              // 业务组件
              componentRulesCode += `       ${formItemName}:[...componentRules['${busname}']({required:${required ? 'true':'false'}})],\n`
            }
            // 
            let otherOptions = {
              otherComponentSettings : ``,
              showSetting : ``,
            }
            if (item.inputType === '只读') {
              let code_readonly = `${formName}_${formItemName}Readonly`
              // 只读的状态变量申明
              varCode += `const ${code_readonly} = ref(true);\n;`
              // 预览代码需要组装totalData信息
              totalData += `
  ${code_readonly},`
              // 组件的其他配置信息
              otherOptions.otherComponentSettings += `\n:readonly="${code_readonly}"`
            }
            if (item.inputType === '禁用') {
              let code_disabled = `${formName}_${formItemName}Disabled`
              varCode += `const ${code_disabled} = ref(true);\n;`
              totalData += `
  ${code_disabled},`
              otherOptions.otherComponentSettings += `\n:disabled="${code_disabled}"`
            }
            if (item.show === false) {
              // 如果设置了隐藏
              let code_show = `${formName}_${formItemName}Show`
              varCode += `const ${code_show} = ref(false);\n`
              totalData += `
  ${code_show},`
              otherOptions.showSetting += `\n v-show="${code_show}"`              
            }
            htmlStrArr.push(componentsFnMap[componentName].getHtmlStr(item,otherOptions))
            let newItem = {
              ...item,
            }
            return newItem
          })    
        // 使用componentRules
        varCode += `\n
const ${layoutItem.formName}Rules = reactive({
  ${componentRulesCode}
});\n`
        totalData += `
  ${layoutItem.formName}Rules,`
        let containerBodyStr = htmlStrArr.join('')
        let rowArr = containerBodyStr.split('\n\r')
        // console.log('%c rowArr','font-size:24px;color:red;',rowArr)
        // 容器相关代码生成
        let layoutHtmlStr = componentsFnMap[layoutItem.componentName].getHtmlStr({...layoutItem,containerBodyStr},layoutOtherOptions)
        return `${layoutHtmlStr}`
    }).join('\n')
    totalData += `\n}`
    let rooId = `root_${pageId}`
    let htmlStr = `
<Fullkeyboard id="${rooId}">
  ${layoutHtml}
</Fullkeyboard>
`
// 其它代码，最终要在.vue文件中运行
let otherCode = `
const defaultLayoutOptions = {
  xs: 12,
  sm: 8,
  md: 8,
  lg: 6,
  xl: 4
};
const currentLayoutOptions = computed(() => {
  return { ...defaultLayoutOptions };
});
`
let scriptStr = `

${varCode} \n
${commentJs}
totalData = ${totalData}     
`  
    return {htmlStr,scriptStr}
}

export function copyToClipboard(str) {
    let tempInput = document.createElement('textarea');
    tempInput.style = 'position: absolute; left: -1000px; top: -1000px';
    tempInput.value = str;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    document.body.removeChild(tempInput);
  }

  export async function generateFiles(htmlContent = '',jsContent = '') {
    // const userStore = useUserStore();
    try {
        const response = await fetch('http://localhost:3000/api/layouts/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'authorization': userStore.token
            },
            body: JSON.stringify({
                htmlContent,
                jsContent
            })
        });

        if (!response.ok) {
            throw new Error('网络响应不正常');
        }

        // 获取二进制数据
        const blob = await response.blob();
        
        // 创建下载链接
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '页面.zip';
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // 清理
        window.URL.revokeObjectURL(downloadUrl);

    } catch (error) {
        console.error('生成文件失败:', error);
        alert('生成文件失败: ' + error.message);
    }
}


function getEventCode (item) {
    let {boxId,eventList = [],labelName} = item
    return eventList.map(eventName => {
        return `
            // ${labelName} ${eventName}
            $("#${boxId}").delegate('input,select,textarea,button', '${eventName}', function () {
                
            });    
        `
    }).join('\n')
}

function traverseTree(treeData,htmlStr) {
    treeData.forEach(treeNode => {
        
    })
}
export function getVueSetupJs () {
  /* 
              ref="formRef"
            require-asterisk-position="right"
            :model="form.props"
            :rules="formRules
  */
  return `
  const formRef = ref();
  const form = reactive({
    props: {}
  });
  // 校验规则
const formRules = reactive({
  product: [
    {
      required: true,
      message: '输入想购买的产品',
      trigger: 'change'
    }
]})
  `
    return `
const defaultLayoutOptions = {
  xs: 12,
  sm: 8,
  md: 8,
  lg: 6,
  xl: 4
};
const currentLayoutOptions = computed(() => {
  return { ...defaultLayoutOptions };
});
interface Tree {
  label: string;
  children?: Tree[];
}
const form = reactive({
  props: {}
});

// 副本数据用于重置表单后赋予初始数据，不必再加載请求
const backFormData = reactive({
  formData: {}
});

const tableLoading = ref(false);
const editorFormRef = ref();
const formRef = ref();
// table测试数据
const uploadRef = ref();
const accountRef = ref();
const rowAccountRef = ref();
const currencyRef = ref();
const rowCurrencyRef = ref();
const orgnoRef = ref();
const rowOrgnoRef = ref();
const tellersRef = ref();
const rowTellersRef = ref();
const typeRef = ref();
const rowTypeRef = ref();
const marriageRef = ref();
const rowMarriageRef = ref();
const idCateRef = ref();
const rowIdCateRef = ref();
const idNumRef = ref();
const rowIdNumRef = ref();
const codeRef = ref();
const rowCodeRef = ref();
window.globalRef = {
  tableLoading,
  editorFormRef,
  formRef,
  uploadRef,
  accountRef,
  rowAccountRef,
  currencyRef,
  rowCurrencyRef,
  orgnoRef,
  rowOrgnoRef,
  tellersRef,
  rowTellersRef,
  typeRef,
  rowTypeRef,
  marriageRef,
  rowMarriageRef,
  idCateRef,
  rowIdCateRef,
  idNumRef,
  rowIdNumRef,
  codeRef,
  rowCodeRef
};
// 账户输入校验结果
const validateAccount = computed(() => {
  return accountRef.value && accountRef.value.validateAccount;
});
// 自定义表单组件
const validateuserList = computed(() => {
  return true;
  console.log(
    '%c form.props.userList',
    'font-size:24px;color:red;',
    form.props.userList
  );
  return true || (form.props.userList && form.props.userList.length > 0);
});

const validatecurrency = computed(() => {
  return currencyRef.value && currencyRef.value.validateCurrency;
});

const validateOrgno = computed(() => {
  return orgnoRef.value && orgnoRef.value.validateOrgno;
});

const validateTellers = computed(() => {
  return tellersRef.value && tellersRef.value.validateTellers;
});

const validateSexType = computed(() => {
  return typeRef.value && typeRef.value.validateSexType;
});

const validateMarType = computed(() => {
  return marriageRef.value && marriageRef.value.validateMarType;
});
const validateCardType = computed(() => {
  return idCateRef.value && idCateRef.value.validateCardType;
});
const validateCard = computed(() => {
  return idNumRef.value && idNumRef.value.validateIdCard;
});

const validateVerification = computed(() => {
  return codeRef.value && codeRef.value.validateVerification;
});

// 账户输入校验结果
const rowValidateAccount = computed(() => {
  return rowAccountRef.value && rowAccountRef.value.validateAccount;
});

const rowValidatecurrency = computed(() => {
  return rowCurrencyRef.value && rowCurrencyRef.value.validateCurrency;
});

const rowValidateOrgno = computed(() => {
  return rowOrgnoRef.value && rowOrgnoRef.value.validateOrgno;
});

const rowValidateTellers = computed(() => {
  return rowTellersRef.value && rowTellersRef.value.validateTellers;
});

const rowValidateSexType = computed(() => {
  return rowTypeRef.value && rowTypeRef.value.validateSexType;
});

const rowValidateMarType = computed(() => {
  return rowMarriageRef.value && rowMarriageRef.value.validateMarType;
});
const rowValidateCardType = computed(() => {
  return rowIdCateRef.value && rowIdCateRef.value.validateCardType;
});
const rowValidateCard = computed(() => {
  return rowIdNumRef.value && rowIdNumRef.value.validateIdCard;
});

const rowValidateVerification = computed(() => {
  return rowCodeRef.value && rowCodeRef.value.validateVerification;
});

const rowFormRules = reactive({
  product: [
    {
      required: true,
      message: '输入想购买的产品',
      trigger: 'change'
    }
  ],
  account: [
    {
      required: true,
      trigger: 'change',
      validator: rowValidateAccount
    }
  ],
  currency: [
    {
      required: true,
      trigger: 'change',
      validator: rowValidatecurrency
    }
  ],
  orgno: [
    {
      required: true,
      trigger: 'change',
      validator: rowValidateOrgno
    }
  ],
  operater: [
    {
      required: true,
      trigger: 'change',
      validator: rowValidateTellers
    }
  ],
  sex: [
    {
      required: true,
      validator: rowValidateSexType,
      trigger: 'change'
    }
  ],
  marriage: [
    {
      required: true,
      validator: rowValidateMarType,
      trigger: 'change'
    }
  ],
  idCardCate: [
    {
      required: true,
      validator: rowValidateCardType,
      trigger: 'change'
    }
  ],
  idNo: [
    {
      required: true,
      validator: rowValidateCard,
      trigger: 'change'
    }
  ],
  mobileNo: [
    {
      required: true,
      validator: rowValidateVerification,
      trigger: 'change'
    }
  ]
});
// 校验规则
const formRules = reactive({
  product: [
    {
      required: true,
      message: '输入想购买的产品',
      trigger: 'change'
    }
  ],
  opCate: [
    {
      required: true,
      message: '输入操作类型',
      trigger: 'change'
    }
  ],
  userList: [
    {
      required: true,
      trigger: 'custom', // custom是随意起的名字
      // validator: validateuserList,
      validator: () => {
        return form.props.userList && form.props.userList.length > 0;
      },
      message: '输入想购买的产品11111'
    }
  ],
  account: [
    {
      required: true,
      trigger: 'change',
      validator: validateAccount
    }
  ],
  currency: [
    {
      required: true,
      trigger: 'change',
      validator: validatecurrency
    }
  ],
  orgno: [
    {
      required: true,
      trigger: 'change',
      validator: validateOrgno
    }
  ],
  operater: [
    {
      required: true,
      trigger: 'change',
      validator: validateTellers
    }
  ],
  sex: [
    {
      required: true,
      validator: validateSexType,
      trigger: 'change'
    }
  ],
  marriage: [
    {
      required: true,
      validator: validateMarType,
      trigger: 'change'
    }
  ],
  idCardCate: [
    {
      required: true,
      validator: validateCardType,
      trigger: 'change'
    }
  ],
  idNo: [
    {
      required: true,
      validator: validateCard,
      trigger: 'change'
    }
  ],
  mobileNo: [
    {
      required: true,
      validator: validateVerification,
      trigger: 'change'
    }
  ]
});

const selectChange = val => {
  if (val != form.props.idCardCate) {
    form.props.idNo = '';
    formRef.value.clearValidate('idNo');
  }
};
const selectChangeRowForm = val => {
  if (val != rowForm.item.idCardCate) {
    rowForm.item.idNo = '';
    editorFormRef.value.clearValidate('idNo');
  }
};

// 组件挂载时赋予初始值
onMounted(async () => {
  const res = await testFormInitApi();
  res.formData.userList = [
    { message: 'aa', id: 'aa' },
    { message: 'bb', id: 'bb' }
  ];
  backFormData.formData = res.formData;
  form.props = res.formData;
  window.baseForm = form;
});

// 共管人选项
const options = [
  {
    value: '张三',
    label: '张三'
  },
  {
    value: '李四',
    label: '李四',
    disabled: true
  },
  {
    value: '王二',
    label: '王二'
  },
  {
    value: '麻子',
    label: '麻子'
  },
  {
    value: '黎明',
    label: '黎明'
  }
];

// 验证码
const vertify = reactive({
  disabled: true,
  validResult: ''
});

// 级别选择
const treeSelectData = [
  {
    value: '1',
    label: 'Level  1',
    children: [
      {
        value: '1-1',
        label: 'Level  1-1',
        children: [
          {
            value: '1-1-1',
            label: 'Level  1-1-1'
          }
        ]
      }
    ]
  },
  {
    value: '2',
    label: 'Level  2',
    children: [
      {
        value: '2-1',
        label: 'Level  2-1',
        children: [
          {
            value: '2-1-1',
            label: 'Level  2-1-1'
          }
        ]
      },
      {
        value: '2-2',
        label: 'Level  2-2',
        children: [
          {
            value: '2-2-1',
            label: 'Level  2-2-1'
          }
        ]
      }
    ]
  },
  {
    value: '3',
    label: 'Level  3',
    children: [
      {
        value: '3-1',
        label: 'Level  3-1',
        children: [
          {
            value: '3-1-1',
            label: 'Level  3-1-1'
          }
        ]
      },
      {
        value: '3-2',
        label: 'Level two 3-2',
        children: [
          {
            value: '3-2-1',
            label: 'Level  3-2-1'
          }
        ]
      }
    ]
  }
];

const optionsCate = [
  {
    label: '客户本人操作',
    value: 'option1'
  },
  {
    label: '柜员操作',
    value: 'option2'
  },
  {
    label: '司法机关操作',
    value: 'option3'
  }
];

const generateData = () => {
  const data: Option[] = [];
  const states = [
    'California',
    'Illinois',
    'Maryland',
    'Texas',
    'Florida',
    'Colorado',
    'Connecticut '
  ];
  const initials = ['CA', 'IL', 'MD', 'TX', 'FL', 'CO', 'CT'];
  states.forEach((city, index) => {
    data.push({
      label: city,
      key: index,
      initial: initials[index]
    });
  });
  return data;
};

const trnsferData = ref<Option[]>(generateData());

// table展示数据
const toList = reactive({
  items: []
});
const currentPage = ref(1);
const pageSize = ref(5);
let formListLength = ref(0);

const handleSizeChange = async (size: number) => {
  tableLoading.value = true;
  await testFormBySizeApi(size)
    .then(res => {
      toList.items = res.slicedList;
      formListLength.value = res.formListLength;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const handleCurrentChange = (currentPage: number) => {
  const size = pageSize.value;
  tableLoading.value = true;
  const res = testFormGetByCurrentPage(currentPage, size)
    .then(res => {
      toList.items = res.handFromList;
      formListLength.value = res.formListLength;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

// 上传文件处理逻辑
const beforeRemove = (uploadFile, uploadFiles) => {
  return MisMessageBox.confirm(\`取消上传 ${uploadFile.name} ?\`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    confirmButtonClass: 'confirmButton',
    type: 'warning'
  }).then(
    () => true,
    () => false
  );
};

const resetForm = formRef => {
  MisMessageBox.confirm(
    '将会重置所有已经输入的表单数据，是否继续?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      confirmButtonClass: 'confirmButton',
      type: 'warning'
    }
  )
    .then(() => {
      formRef.resetFields();
      form.props = backFormData.formData;
    })
    .catch();
};

// 提交处理
const onSubmit = async formRef => {
  if (!formRef) return;
  const size = pageSize.value;
  const page = currentPage.value;
  const props = form.props;
  await formRef.validate((valid, fields) => {
    if (valid) {
      tableLoading.value = true;
      // 发送请求
      testFormAddApi(props, size, page)
        .then(res => {
          toList.items = res.handFromList;
          formListLength.value = res.formListLength;
          MisMessage({
            message: '提交成功',
            type: 'success'
          });
        })
        .finally(() => {
          tableLoading.value = false;
        });
    }
  });
};

const vertifyDisabled = ref(true);
const rowForm = reactive({
  item: {}
});
let rowFormIndex: Number;
let dialogFormVisible = ref(false);
let drawerVisible = ref(false);
let drawerView = reactive({});

const handleEdit = (index, row) => {
  rowForm.item = row;
  rowFormIndex = index;
  dialogFormVisible.value = true;
};

const dialogConfirm = async editorFormRef => {
  if (!editorFormRef) return;
  const size = pageSize.value;
  const page = currentPage.value;
  const item = rowForm.item;
  await editorFormRef.validate((valid, fields) => {
    if (valid) {
      // 发送请求
      console.log('rowForm', rowForm.item);
      testFormEdit(item, rowFormIndex, size, page)
        .then(res => {
          rowForm.item = res.handFromList;
        })
        .finally(() => {
          dialogFormVisible.value = false;
        });
    }
  });
};

const handleDeleteConfirm = (index, row) => {
  const size = pageSize.value;
  const page = currentPage.value;
  tableLoading.value = true;
  testFormDelApi(index, page, size)
    .then(res => {
      toList.items = res.handFromList;
      formListLength.value = res.formListLength;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const handleDrawer = row => {
  // 赋值
  drawerView = row;
  drawerVisible.value = true;
};

const handleExceed = files => {
  form.items.uploadFileList.clearFiles();
};

const formatterCardCate = row => {
  for (let i = 0; i < Card.length; i++) {
    if (Card[i].value == row.idCardCate) {
      return Card[i].label;
    }
  }
};

// addr 转换 ---begin
const formatterAddr = row => {
  let resultAddr = '';
  for (let i = 0; i < Addr.length; i++) {
    if (Addr[i].value == row.addr[0]) {
      resultAddr = resultAddr + Addr[i].label;
      for (let j = 0; j < Addr[i].children.length; j++) {
        if (Addr[i].children[j].value == row.addr[1]) {
          resultAddr = resultAddr + Addr[i].children[j].label;
          for (let k = 0; k < Addr[i].children[j].children.length; k++) {
            if (Addr[i].children[j].children[k].value == row.addr[2]) {
              resultAddr = resultAddr + Addr[i].children[j].children[k].label;
              for (
                let m = 0;
                m < Addr[i].children[j].children[k].children.length;
                m++
              ) {
                if (
                  Addr[i].children[j].children[k].children[m].value ==
                  row.addr[3]
                ) {
                  return (resultAddr =
                    resultAddr +
                    Addr[i].children[j].children[k].children[m].label);
                }
              }
            }
          }
        }
      }
    }
  }
  // addr 转换 ---end
};

const formatteropCate = row => {
  let opResult = '';
  for (let i = 0; i < row.opCate.length; i++) {
    for (let j = 0; j < optionsCate.length; j++) {
      if (optionsCate[j].value === row.opCate[i]) {
        opResult = opResult + optionsCate[j].label + ' ';
      }
    }
  }
  return opResult;
};

const formatterCity = row => {
  const convertData = generateData();
  let cityResult = '';
  for (let i = 0; i < row.transferdata.length; i++) {
    for (let j = 0; j < convertData.length; j++) {
      if (convertData[j].key === row.transferdata[i]) {
        cityResult = cityResult + convertData[j].label + ' ';
      }
    }
  }
  return cityResult;
};

const formatterFile = row => {
  let fileNameArry: any = [];
  row.uploadFileList.forEach(element => {
    fileNameArry.push(element.name);
  });
  return fileNameArry.join(',');
};    
    `
}